package com.huifai.common.interceptor;

import com.huifai.common.cache.RedisService;
import com.huifai.common.constant.ERespCode;
import com.huifai.common.constant.SysConstant;
import com.huifai.common.exception.BaseException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * <br>==========================
 * <br> 创建人：吴传军
 * <br> 创建时间：2019/8/7 16:46
 * <br> 版本：1.0
 * <br> 描述：权限控制拦截器
 * <br>==========================
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        String token = httpServletRequest.getHeader("AccessToken");// 从 http 请求头中取出 token
        if(StringUtils.isEmpty(token)){
            throw new BaseException(ERespCode.TOKEN_NULL);
        }
        String userId=redisService.get(token);
        if(StringUtils.isEmpty(userId)){
            throw new BaseException(ERespCode.TOKEN_ERROR);
        }
        httpServletRequest.setAttribute(SysConstant.CURRENT_USER,redisService.get(SysConstant.USER_PREFIX+userId));
        return true;
        }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
